//
//  TGChooseFileViewController.m
//  TongGuanLease
//
//  Created by Henghuitong on 2022/6/22.
//

#import "TGChooseFileViewController.h"
#import "TGChooseFile.h"
#import "GetMIMEType.h"
#import "TGMusicPlayVC.h"

//#import <MobileCoreServices/MobileCoreServices.h>


@interface TGChooseFileViewController ()<UIDocumentPickerDelegate, UIDocumentInteractionControllerDelegate>


@property (nonatomic, strong) UITextView *tv;

@end

@implementation TGChooseFileViewController


- (void)setupNavigationItems
{
    [super setupNavigationItems];
    
    [self setNavStyleRedAndBackBtn];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择文件";
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor redColor];
    [btn setTitle:@"选择文件" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(100, 100));
        make.top.mas_equalTo(self.view);
    }];
    
    self.tv= [[UITextView alloc]init];
    self.tv.textColor =   [UIColor blackColor];;
    self.tv.font = TGMediumAFont(20);
    self.tv.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:self.tv];
    
    [self.tv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(btn.mas_bottom).offset(10);
        make.bottom.left.right.mas_equalTo(self.view);
    }];
    
}


-(void)btnClick
{
//    [self openDocumentPickerViewController];
    [TGChooseFileSharedInstance chooseFileWithSelectVC:self success:^(NSArray * _Nonnull array) {
  
        NSLog(@"文件全部上传成功返回数据---- %@",array);
        self.tv.text = [array objectToJSON];
        NSDictionary *dic = array.firstObject;
        NSString *url = dic[@"url"];
        
        TGMusicPlayVC *vc = [[TGMusicPlayVC alloc] init];
        vc.url = [NSString stringWithFormat:@"https://tgzlosstest.oss-cn-beijing.aliyuncs.com/%@", url];
        
        [self pushViewController:vc complent:nil];
    }];
  
    
}

- (void)loadListMenuWithFinishMark:(NSURL *)url{
    
    
    __block NSError *error;
    
    
    // 创建信号量
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    
    //获取授权
    BOOL fileUrlAuthozied = [url startAccessingSecurityScopedResource];
    if(fileUrlAuthozied){
        //通过文件协调工具来得到新的文件地址，以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
            NSLog(@"选择的文件地址=== %@",newURL.absoluteString);
            
            
          
            //读取文件
            NSString *fileName = [newURL lastPathComponent];
            NSLog(@"文件名称=== %@",fileName);

            NSString *fileMIMETypeWithCAPI = [GetMIMEType getMIMETypeWithCAPIAtFilePath:newURL.absoluteString];
            NSLog(@"fileMIMETypeWithCAPI===%@",fileMIMETypeWithCAPI);
            
          
            
            
            NSError *error = nil;
            NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];

        
            NSString *newNameStr = [fileName stringByRemovingPercentEncoding];
            NSArray *fileArray = [newNameStr componentsSeparatedByString:@"."];
    //            NSString *mimeType = [NSString stringWithFormat:@"application/%@",fileArray.lastObject];
            NSString *mimeType = [NSString stringWithFormat:@"file/%@",fileArray.lastObject];


//            [TGGCD executeMainAsyncTask:^{
//
//                [TGProgressHUD showHUD:nil];
//            }];

            /*
            [TGNetworkManager uploadFileWithFileData:fileData fileUrl:newURL fileName:fileName filePath:@"CRM_SERVICE" mimeType:mimeType success:^(TGResponseItem *responseItem) {

//                [TGGCD executeMainAsyncTask:^{
//                    [TGProgressHUD dismissMPHUD];
//
//                }];


                [url stopAccessingSecurityScopedResource];

                dispatch_semaphore_signal(sema);

                if (responseItem.success) {
                    NSLog(@"上传文件成功返回数据=====%@",responseItem.data);
    //                    [TGProgressHUD showMBHUDErrorTip:@"上传成功"];
                }else
                {
//                    [TGProgressHUD showMBHUDErrorTip:responseItem.message];
                    [url stopAccessingSecurityScopedResource];
                    dispatch_semaphore_signal(sema);
                }

            } failure:^(NSError *error) {
                
//                [TGGCD executeMainAsyncTask:^{
//                    [TGProgressHUD showHUDTipNetError];
//                }];
                
                [url stopAccessingSecurityScopedResource];
                dispatch_semaphore_signal(sema);

                return;

            }];
*/

        }];


    }else{
//        [TGProgressHUD showMBHUDErrorTip:@"授权失败"];
        dispatch_semaphore_signal(sema);

    }
    
    
    
//    NSString *urlString = @"http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
//     [[AFHTTPSessionManager manager] GET:urlString parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//         dispatch_semaphore_signal(sema);
//         NSLog(@"结束======%ld",index);
//     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//         dispatch_semaphore_signal(sema);
//         NSLog(@"结束======%ld", index);
//     }];
    
    
     dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    
    
//    NSString *urlString = @"http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
//
//    [[AFHTTPSessionManager manager] GET:urlString parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        // 发送信号 （+ 1）
//        dispatch_semaphore_signal(sema);
//        NSLog(@"结束======%@",url);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        dispatch_semaphore_signal(sema);
//        NSLog(@"结束======%@", url);
//    }];
//
//
//    // 等待signal执行+1后（>0），才执行wait后的业务
//    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    
    
}




- (void)openDocumentPickerViewController{
    // 设置文件类型
    NSArray *documentTypes = @[@"public.content",
                               @"public.text",
                               @"public.source-code ",
                               @"public.image",
                               @"public.audiovisual-content",
                               @"com.adobe.pdf",
                               @"com.apple.keynote.key",
                               @"com.microsoft.word.doc",
                               @"com.microsoft.excel.xls",
                               @"com.microsoft.powerpoint.ppt"];
    
    // 因为在Appdelegate中我设置了UIScrollViewContentInsetAdjustmentNever，这里需要修改为UIScrollViewContentInsetAdjustmentAutomatic，否则界面会上移
//    if (@available(iOS 11, *)) {
//        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
//    }
    
    UIDocumentPickerViewController *documentPickerViewController = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
    documentPickerViewController.delegate = self;
    documentPickerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:documentPickerViewController animated:YES completion:nil];
}


#pragma mark 点击取消文件选择
- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller{
    /// 设置回UIScrollViewContentInsetAdjustmentNever
    if (@available(iOS 11, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

#pragma mark 点击选择文件结果
//- (void)documentPicker:(UIDocumentPickerViewController *)controller
//  didPickDocumentAtURL:(NSURL *)url
//{
//
//
//    NSLog(@"文件路径=%@",url);
//
//    BOOL canAccessingResource = [url startAccessingSecurityScopedResource];
//
//    if(canAccessingResource) {
//
//        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
//        NSError *error;
//        [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
//            NSData *fileData = [NSData dataWithContentsOfURL:newURL];
//            NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//            NSString *documentPath = [arr lastObject];
//            NSString *desFileName = [documentPath stringByAppendingPathComponent:@"myFile.pdf"];
//            [fileData writeToFile:desFileName atomically:YES];
//            [self dismissViewControllerAnimated:YES completion:NULL];
//             }];
//        if (error) {
//            // error handing
//        }
//    } else {
//        // startAccessingSecurityScopedResource fail
//    }
//    [url stopAccessingSecurityScopedResource];
//
//}



- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
    /// 设置回UIScrollViewContentInsetAdjustmentNever
    if (@available(iOS 11, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    BOOL fileUrlAuthozied = [url startAccessingSecurityScopedResource];
    if(fileUrlAuthozied){
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
            NSLog(@"选择的文件地址=== %@",newURL.absoluteString);
//            [HttpRequest uploadMediaWithType:uploadMediaType_Doc docUrl:newURL imageData:nil];
        }];
        [url stopAccessingSecurityScopedResource];
    }else{
//        [self showToastTips:@"此文件不可用"];
        NSLog(@"此文件不可用");
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
